package bjut.zrpc.core.optimization.loadbalance;

import bjut.zrpc.core.optimization.interfaces.LoadBalance;
import bjut.zrpc.core.optimization.message.ZRpcRequestMessage;
import bjut.zrpc.core.optimization.protect.ServicesRecord;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @Author: zhuzhiming
 * @Date: 2022/6/24 20:00
 */
public abstract class AbstractLoadBalance implements LoadBalance {


    @Override
    public String selectService(List<String> serviceList, ZRpcRequestMessage zRpcRequestMessage) {

        if (CollectionUtils.isEmpty(serviceList)) {
            throw new RuntimeException("no available service");
        } else if (serviceList.size() == 1) {
            ServicesRecord.SERVICES_MAP.put(zRpcRequestMessage.getServiceInfo(), serviceList);
            return serviceList.get(0);
        }

        return doSelect(serviceList, zRpcRequestMessage);
    }

    protected abstract String doSelect(List<String> serviceList, ZRpcRequestMessage zRpcRequestMessage);
}
